<?php


namespace app\api\controller\v20;


use app\api\controller\v2\Auth;
use app\common\cachemodel\ZlAstrExerciseRecord;
use app\common\lib\exception\ApiException;
use think\Controller;
use think\Env;
use think\Exception;
use think\Log;

/**
 * @version 2.4.0
 * Class StarActivRanking
 * @package app\api\controller\v20
 */
class StarActivRanking extends Controller
{
    /**
     * 获取排行榜信息
     */
    public function getRanking()
    {
        $oss = Env::get('host.photo');
        $headers = $this->request->header();
        if (isset($headers['access-token'], $headers['app-type'], $headers['sign']))
        {
            //校验token
            try
            {
                $auth = new Auth();
                $auth->checkRequestAuth();
                $userInfo = $auth->user;
            }
            catch (Exception $e)
            {
                Log::write('占星师挑战活动服务异常：' . $e->getMessage(), 'error', true);
                return show(config('code.success'),'服务异常；请稍后再试～');
            }
        } else
        {
            $userInfo = [];
        }
        if ($userInfo)
        {
            // 获取用户当前答题状态信息
            $userAnswerInfo = (new ZlAstrExerciseRecord())->getInfoById($userInfo['id']);
            if ($userAnswerInfo && ($userAnswerInfo['grade'] > 0 || ($userAnswerInfo['status'] == 2)))
            {
                $grade = $userAnswerInfo['grade'];
                $status = 2;
            } else
            {
                $grade = 0;
                $status = 1;
            }
            $activStatus = 0; // 未参加挑战
            if ($userAnswerInfo)
            {
                if ($userAnswerInfo['status'] == 2)
                {
                    $activStatus = 2; // 挑战结束
                } else
                {
                    $activStatus = 1; // 挑战中
                    if ($userAnswerInfo['level'] == 4)
                    { // 在第四关
                        $content4 = json_decode($userAnswerInfo['content4'], true);
                        if ($content4 && $content4['answer'])
                        { // 已经回答过问题了
                            $activStatus = 2; // 挑战结束
                        }
                    }
                }
            }
        } else
        {
            $activStatus = 0;
            $grade = 0;
            $status = 1;
        }
        $rankingPageData = (new ZlAstrExerciseRecord())->getRanking($userInfo, $oss, $grade, $status);
        $rankingPageData['status'] = $activStatus;

        return show(config('code.success'), '获取成功', $rankingPageData);
    }
}
